<?php
/**
 * Created by PhpStorm.
 * User: minicart
 * Date: 2018/9/22
 * Time: 11:56
 */
namespace app\admin\service;
use app\models\MenuModel;

class MenuService
{
    /**
     * 菜单列表
     * @return array
     */
    public function lists()
    {
        try {
            $page = input('page',1);
            $listRows = input('limit',10);
            $where = [];
            $where['pid'] = input('param.pid', 0);
            $order = 'sort,id asc';
            $result = MenuModel::pageLists($where,$page,$listRows,$order);
            return $result;
        } catch (\Exception $ex) {
            return ['code' => 1, 'msg' => $ex->getMessage()];
        }
    }

    /**
     * 添加菜单
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        $data = input('post.');
        $menuModel = new MenuModel();
        $data['is_menu'] = 1;
        //添加的菜单是否是三級菜单
        if ($data['pid']) {
            $data['is_menu'] = $menuModel->isSecondaryMenu($data['pid']) ? 2 : 1;
        }
        if (!($data['controller'] && !$data['action'] || $data['action'] == '*' && $data['controller'] == '*')) {
            if ($menuModel->isExistOpt($data['controller'], $data['action'])) {
                return ['code' => 1, 'msg' => "该菜单已存在"];
            }
        }
        if ($menuModel->addMenu($data)) {
            return ['code' => 0, 'msg' => "添加成功"];
        }
        return ['code' => 1, 'msg' => "添加失败"];
    }

    /**
     * 修改菜单
     * @return array
     */
    public function edit()
    {
        $data = input('post.');
        $menuModel = new MenuModel();
        $result = $menuModel->editMenu($data);
        if ($result !== false) {
            return ['code' => 0, 'msg' => "修改成功"];
        }
        return ['code' => 1, 'msg' => "修改失败"];
    }

    /**
     * 删除菜单
     * @param $id
     * @return array
     */
    public function del($id)
    {
        $menuModel = new MenuModel();
        $result = $menuModel->delMenu($id);
        if ($result !== false) {
            return ['code' => 0, 'msg' => "删除成功"];
        }
        return ['code' => 1, 'msg' => "删除失败"];
    }
}